package com.itheima.datastructure;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class E02Leetcode102 {

    public static void main(String[] args) {

        LinkedList<TreeNode> list = new LinkedList<>();
        TreeNode root = new TreeNode(
                new TreeNode(new TreeNode(4), 2, new TreeNode(5)),
                1,
                new TreeNode(new TreeNode(6), 3, new TreeNode(7))
        );

        List<List<Integer>> tree = levelOrder(root);
        System.out.println(tree);
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        LinkedList<TreeNode> list = new LinkedList<>();
        list.offer(root);
        int k1 = 1; // 一开始root根节点只有一个元素
        while (!list.isEmpty()) {
            int k2 = 0; // 记录下面每一行节点有几个元素
            ArrayList<Integer> rL = new ArrayList<>();
            for (int i = 0; i < k1; i++) {
                TreeNode ele = list.poll();
                rL.add(ele.val);
                if (ele.left != null) {
                    list.offer(ele.left);
                    k2++;
                }
                if (ele.right != null) {
                    list.offer(ele.right);
                    k2++;
                }
            }
            k1 = k2;
            result.add(rL);
        }
        return result;
    }
}
